package com.xuecheng.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.constant.CourseTeacherError;
import com.xuecheng.exception.XueChengPlusException;
import com.xuecheng.mapper.CourseTeacherMapper;
import com.xuecheng.po.CourseTeacher;
import com.xuecheng.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 课程-教师关系 服务实现类
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {
	
	@Override
	public CourseTeacher addCourseTeacher(CourseTeacher courseTeacher) {
		CourseTeacher teacher = getOne(Wrappers.<CourseTeacher>lambdaQuery().eq(CourseTeacher::getCourseId,
			courseTeacher.getCourseId()).eq(CourseTeacher::getTeacherName, courseTeacher.getTeacherName()));
		if (teacher != null) {
			log.error(CourseTeacherError.COURSE_TEACHER_NOT_EMPTY);
			throw new XueChengPlusException(CourseTeacherError.COURSE_TEACHER_NOT_EMPTY);
		}
		courseTeacher.setCreateDate(LocalDateTime.now());
		boolean save = save(courseTeacher);
		if (!save) {
			log.error(CourseTeacherError.ADD_COURSE_TEACHER_ERROR);
			throw new XueChengPlusException(CourseTeacherError.ADD_COURSE_TEACHER_ERROR);
		}
		return getOne(Wrappers.<CourseTeacher>lambdaQuery().eq(CourseTeacher::getCourseId,
			courseTeacher.getCourseId()).eq(CourseTeacher::getTeacherName, courseTeacher.getTeacherName()).eq(CourseTeacher::getPosition, courseTeacher.getPosition()));
	}
	
	@Override
	public CourseTeacher updateCourseTeacher(CourseTeacher courseTeacher) {
		boolean update = updateById(courseTeacher);
		if (!update) {
			log.error(CourseTeacherError.UPDATE_COURSE_TEACHER_ERROR);
			throw new XueChengPlusException(CourseTeacherError.UPDATE_COURSE_TEACHER_ERROR);
		}
		return getById(courseTeacher.getId());
	}
}
